package com.plum.admin.config.security.filter;

import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.plum.admin.common.constant.Constant;
import com.plum.admin.common.util.ResponseUtil;
import com.plum.admin.common.vo.TokenUser;
import com.plum.admin.config.security.SecurityUserDetails;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @author 子丶沫
 * @version 1.0
 * @date 2021/8/13 14:42
 */
@Component
@Slf4j
public class LogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String header = request.getHeader(Constant.HEADER);
        if(StrUtil.isBlank(header)){
            header=request.getParameter(Constant.HEADER);
        }
        String token = redisTemplate.opsForValue().get(Constant.TOKEN_PRE + header.split(" ")[1]);
        TokenUser tokenUser = new Gson().fromJson(token, TokenUser.class);
        String username=tokenUser.getUsername();
        String oldToken = redisTemplate.opsForValue().get(Constant.USER_TOKEN + username);
        if(StrUtil.isNotBlank(oldToken)){
            redisTemplate.delete(Lists.newArrayList(Constant.USER_TOKEN + username,Constant.TOKEN_PRE+oldToken));
        }
        ResponseUtil.out(response,ResponseUtil.resultMap(200,"退出登录成功....."));
    }
}
